package org.wlgzs.office_exam_student.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wlgzs.office_exam_student.entity.Role;
import org.wlgzs.office_exam_student.entity.User;
import org.wlgzs.office_exam_student.permission.Authentication;

import com.songminju.jdagger.JDCheck;

/**
*@author song(mejeesong@qq.com)
*2018年3月12日
*
*/
@WebFilter("/*")
public class LoginFilter implements Filter {

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	private String contextPath = null;
	private final String loginPath = "/login.html";
	private final String logoutPath = "/logout";
	private final String loginApiPath = "/api/login";
	private final String vcodePath = "/login-vcode";
	private final String staticPath = "/static/";
	private String redirectMyInfoPath = null;
	private String redirectLoginPath = null;
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		contextPath = filterConfig.getServletContext().getContextPath();
		redirectLoginPath = contextPath +loginPath;
		redirectMyInfoPath = contextPath + "/myInfo";
		logger.debug(contextPath);
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		
		HttpServletRequest req = (HttpServletRequest)request;
		String uri = req.getRequestURI();
		uri = uri.substring(contextPath.length());
		if(uri.startsWith(staticPath) || JDCheck.hasEquals(uri,loginPath,vcodePath,loginApiPath,logoutPath)) {
			chain.doFilter(request, response);
			return;
		}
		HttpServletResponse resp = (HttpServletResponse)response;
		if(Authentication.is(req, Role.STUDENT)){
			User user = Authentication.user(req);
			logger.debug(user.toString());
			if(JDCheck.hasNsNull(user.getPhone(),user.getName())) {
				if(!uri.equals("/myInfo")) {
					resp.sendRedirect(redirectMyInfoPath);
					return;
				}
			}
			chain.doFilter(request, response);
		}else {
			resp.sendRedirect(redirectLoginPath);
		}
	}

	@Override
	public void destroy() {
	}
	
}
